package dao

import (
	"bytes"
	"encoding/json"
	"fmt"
	"git.supremind.info/product/box/vehicle/common"
)

type Role struct {
	BaseModel
	CompanyId   int
	Application string
	Name        string
	Description string
	Permissions string
	Child       string
}

func (c *Role) TableName() string {
	return "role"
}

func (c *Role) ToJsonStr() string {
	marshal, err := json.Marshal(c)
	if err != nil {
		return ""
	}
	return string(marshal)
}

func SelectAllRole() *[]Role {
	role := make([]Role, 0)
	DB.Where("is_del = ?", 0).Find(&role)
	return &role
}

func SelectRoleByExample(role *Role) *[]Role {
	roles := make([]Role, 0)
	DB.Where(&role)
	DB.Find(&roles)
	return &roles
}

func SaveRole(role *Role) int {
	DB.Create(&role)
	return role.ID
}

func SaveRoleBatch(roles *[]Role) error {
	//for _, role := range *roles {
	//	DB.Create(&role)
	//}
	var buffer bytes.Buffer
	sql := "insert into `role` (company_id, application, name, description, permissions, child, is_del, create_by, create_time, update_by, update_time) values "
	if _, err := buffer.WriteString(sql); err != nil {
		return err
	}
	for i, e := range *roles {
		createTime, _ := e.CreateTime.MarshalJSON()
		updateTime, _ := e.UpdateTime.MarshalJSON()
		if i == len(*roles)-1 {
			buffer.WriteString(fmt.Sprintf("(%d,'%s','%s','%s','%s','%s',%d,%d,%s,'%d',%s);", e.CompanyId, e.Application, e.Name, e.Description, e.Permissions, e.Child, e.IsDel, e.CreateBy, string(createTime), e.UpdateBy, string(updateTime)))
		} else {
			buffer.WriteString(fmt.Sprintf("(%d,'%s','%s','%s','%s','%s',%d,%d,%s,'%d',%s),", e.CompanyId, e.Application, e.Name, e.Description, e.Permissions, e.Child, e.IsDel, e.CreateBy, string(createTime), e.UpdateBy, string(updateTime)))
		}
	}
	common.Logger.Infof("%s", buffer.String())
	return DB.Exec(buffer.String()).Error
}

func UpdateRole(role *Role) {
	DB.Model(&role).Save(&role)
}

func DeleteRole(id int) {
	role := Role{}
	role.ID = id
	DB.Delete(role)
}

func DeleteRoleByExample(role *Role) {
	DB.Where(&role).Delete(Role{})
}
